<template>
  <div class="deploy-container">
    <div class="deploy-card">
      <h1>部署新应用</h1>
      
      <form @submit.prevent="handleDeploy" class="deploy-form">
        <!-- 应用基本信息 -->
        <div class="form-group">
          <label for="appName">应用名称:</label>
          <input 
            type="text" 
            id="appName" 
            v-model="formData.name" 
            required 
            placeholder="输入应用名称"
          >
        </div>

        <div class="form-group">
          <label for="dockerImage">Docker 镜像:</label>
          <input 
            type="text" 
            id="dockerImage" 
            v-model="formData.image" 
            placeholder="例如: nginx:latest" 
            required
          >
        </div>

        <div class="form-group">
          <label for="replicas">副本数:</label>
          <input 
            type="number" 
            id="replicas" 
            v-model.number="formData.replicas" 
            min="1" 
            required
          >
        </div>

        <!-- 资源配置 -->
        <div class="row">
          <div class="form-group">
            <label for="cpu">CPU (Core):</label>
            <input 
              type="text" 
              id="cpu" 
              v-model="formData.cpu" 
              placeholder="例如: 0.5 或 500m" 
              required
            >
          </div>
          <div class="form-group">
            <label for="memory">内存 (MiB/GiB):</label>
            <input 
              type="text" 
              id="memory" 
              v-model="formData.memory" 
              placeholder="例如: 512Mi 或 1Gi" 
              required
            >
          </div>
        </div>

        <div class="form-group">
          <label for="storage">磁盘空间 (GiB):</label>
          <input 
            type="text" 
            id="storage" 
            v-model="formData.storage" 
            placeholder="例如: 10Gi (留空则不挂载存储)"
          >
        </div>

        <!-- 容器端口 -->
        <div class="form-group">
          <label>容器端口:</label>
          <div class="container-ports">
            <div 
              v-for="(port, index) in formData.containerPorts" 
              :key="index" 
              class="port-row"
            >
              <input 
                type="number" 
                v-model.number="formData.containerPorts[index]" 
                placeholder="例如: 80" 
                required
              >
              <button 
                type="button" 
                class="remove-btn" 
                @click="removeContainerPort(index)"
                :disabled="formData.containerPorts.length <= 1"
              >
                -
              </button>
            </div>
          </div>
          <button type="button" @click="addContainerPort" class="add-btn">添加端口</button>
        </div>

        <!-- 服务类型 -->
        <div class="form-group">
          <label for="serviceType">服务类型:</label>
          <select id="serviceType" v-model="formData.serviceType">
            <option value="ClusterIP">ClusterIP</option>
            <option value="NodePort">NodePort</option>
            <option value="LoadBalancer">LoadBalancer</option>
          </select>
        </div>

        <!-- 端口映射 -->
        <div class="form-group">
          <label>端口映射 (容器端口 -> 服务端口):</label>
          <table class="port-mapping-table">
            <thead>
              <tr>
                <th>容器端口</th>
                <th>服务端口</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(mapping, index) in formData.portMappings" :key="index">
                <td>
                  <input 
                    type="number" 
                    v-model.number="mapping.containerPort" 
                    placeholder="例如: 80" 
                    required
                  >
                </td>
                <td>
                  <input 
                    type="number" 
                    v-model.number="mapping.servicePort" 
                    placeholder="例如: 8080" 
                    required
                  >
                </td>
                <td>
                  <button 
                    type="button" 
                    class="remove-btn" 
                    @click="removePortMapping(index)"
                  >
                    -
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
          <button type="button" @click="addPortMapping" class="add-btn">添加映射</button>
        </div>

        <!-- 命名空间 -->
        <div class="form-group">
          <label for="namespace">命名空间:</label>
          <input 
            type="text" 
            id="namespace" 
            v-model="formData.namespace" 
            required
          >
        </div>

        <!-- 部署按钮 -->
        <button 
          type="submit" 
          class="deploy-button" 
          :disabled="deploying"
        >
          {{ deploying ? '部署中...' : '立即部署' }}
        </button>
      </form>

      <!-- 消息提示 -->
      <div 
        v-if="message.text" 
        :class="['message', message.type]"
      >
        {{ message.text }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import axios from 'axios'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

// 表单数据
const formData = reactive({
  name: '',
  image: '',
  replicas: 1,
  cpu: '',
  memory: '',
  storage: '',
  containerPorts: [80],
  serviceType: 'ClusterIP',
  portMappings: [{ containerPort: 80, servicePort: 8080 }],
  namespace: 'default'
})

// 状态管理
const deploying = ref(false)
const message = reactive({
  text: '',
  type: ''
})

// 添加容器端口
const addContainerPort = () => {
  formData.containerPorts.push(80)
}

// 移除容器端口
const removeContainerPort = (index: number) => {
  if (formData.containerPorts.length > 1) {
    formData.containerPorts.splice(index, 1)
  }
}

// 添加端口映射
const addPortMapping = () => {
  formData.portMappings.push({ containerPort: 80, servicePort: 8080 })
}

// 移除端口映射
const removePortMapping = (index: number) => {
  formData.portMappings.splice(index, 1)
}

// 显示消息
const showMessage = (text: string, type: 'success' | 'error') => {
  message.text = text
  message.type = type
  
  // 3秒后自动清除消息
  setTimeout(() => {
    message.text = ''
    message.type = ''
  }, 3000)
}

// 处理部署
const handleDeploy = async () => {
  // 基本验证
  if (formData.containerPorts.length === 0) {
    showMessage('请至少指定一个容器端口。', 'error')
    return
  }
  
  if (formData.portMappings.length === 0) {
    showMessage('请至少添加一个端口映射。', 'error')
    return
  }

  deploying.value = true

  try {
    const deployData = {
      ...formData,
      storage: formData.storage || null,
      containerPorts: formData.containerPorts.filter(port => !isNaN(port)),
      portMappings: formData.portMappings.filter(mapping => 
        !isNaN(mapping.containerPort) && !isNaN(mapping.servicePort)
      )
    }

    const response = await axios.post('/api/deploy', deployData, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })

    showMessage(`应用 "${formData.name}" 部署成功!`, 'success')
    
    // 可选：重置表单
    // resetForm()
    
  } catch (error: any) {
    console.error('部署失败:', error)
    
    const errorMessage = error.response?.data?.message || error.message || '部署失败'
    showMessage(`部署失败: ${errorMessage}`, 'error')
  } finally {
    deploying.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    image: '',
    replicas: 1,
    cpu: '',
    memory: '',
    storage: '',
    containerPorts: [80],
    serviceType: 'ClusterIP',
    portMappings: [{ containerPort: 80, servicePort: 8080 }],
    namespace: 'default'
  })
}
</script>

<style scoped>
.deploy-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.deploy-card {
  max-width: 800px;
  margin: 0 auto;
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 28px;
}

.deploy-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

label {
  margin-bottom: 8px;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

input, select {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s;
}

input:focus, select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.row {
  display: flex;
  gap: 15px;
}

.row .form-group {
  flex: 1;
}

/* 容器端口样式 */
.container-ports {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 10px;
}

.port-row {
  display: flex;
  align-items: center;
  gap: 10px;
}

.port-row input {
  flex: 1;
}

/* 端口映射表格 */
.port-mapping-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 10px;
}

.port-mapping-table th,
.port-mapping-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: left;
}

.port-mapping-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.port-mapping-table td input {
  width: 100%;
  margin: 0;
}

/* 按钮样式 */
.add-btn, .remove-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: background-color 0.2s;
}

.add-btn {
  background-color: #10b981;
  color: white;
}

.add-btn:hover {
  background-color: #059669;
}

.remove-btn {
  background-color: #ef4444;
  color: white;
  min-width: 32px;
}

.remove-btn:hover:not(:disabled) {
  background-color: #dc2626;
}

.remove-btn:disabled {
  background-color: #d1d5db;
  cursor: not-allowed;
}

.deploy-button {
  width: 100%;
  padding: 16px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.2s;
  margin-top: 20px;
}

.deploy-button:hover:not(:disabled) {
  background-color: #2563eb;
}

.deploy-button:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

/* 消息提示 */
.message {
  margin-top: 20px;
  padding: 16px;
  border-radius: 6px;
  text-align: center;
  font-weight: 500;
}

.message.success {
  background-color: #d1fae5;
  color: #065f46;
  border: 1px solid #a7f3d0;
}

.message.error {
  background-color: #fee2e2;
  color: #991b1b;
  border: 1px solid #fecaca;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .deploy-container {
    padding: 10px;
  }

  .deploy-card {
    padding: 20px;
  }

  .row {
    flex-direction: column;
  }

  h1 {
    font-size: 24px;
  }
}
</style>
